<template>
  <div class="home">
    <jm-head></jm-head>
    <section class="center">

      <section class="nav" @click="freshen">
        <section class="nav-item"
                 @click="selected = 1">
          <span :class="{'is-selected': selected === 1}">默认</span>
        </section>
        <section class="nav-item"
                 @click="selected = 2">
          <span :class="{'is-selected': selected === 2}">最新</span>
        </section>
        <section class="nav-item"
                 @click="selected = 3">
          <span :class="{'is-selected': selected === 3}">收藏</span>
        </section>
      </section>

      <ul class="post_list_ul" v-infinite-scroll="loadMore"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="10">
        <li class="post_list_li" v-for="item in artilceList" :key="item.id">
          <section class="li_header">
            <section class="li_header_left">
              <img :src="$store.state.baseImgUrl+item.authorAvatar" alt="" class="avatar">
            </section>
            <section class="li_header_center">
              <span class="nick">{{item.authorNick}}</span>
            </section>
            <section class="li_header_right">
              <span class="datetime">{{item.createTime | time}}</span>
            </section>
          </section>

          <section class="li_center" @click="showArticle(item)">
            <section :class="[item.cover3 !== null && item.cover3 !==''? 'li_center_container' : 'li_center_container_active']">
              <span class="container" v-html="item.title"></span>
              <span v-show="item.cover1 !== null && item.cover1 !==''" class="img_show">
                <img v-show="item.cover1 !== null && item.cover1 !==''" :src="item.cover1" alt="" class="img_show_item">
                <img v-show="item.cover3 !== null && item.cover3 !==''" :src="item.cover2" alt="" class="img_show_item">
                <img v-show="item.cover3 !== null && item.cover3 !==''" :src="item.cover3" alt="" class="img_show_item">
              </span>
            </section>
          </section>

          <section class="li_footer">
            <section class="li_footer_item">
              <i class="icon_style iconfont icon-zan"
                 :class="{'icon_style_active':item.upvote}"
                  @click="upvote(item)">点赞：</i>
              <span :class="{'is_selected':item.upvote}">{{item.upvoteCount}}</span>
            </section>
            <section class="li_footer_item">
              <i class="icon_style iconfont icon-xiaoxizhongxin" @click="comment(item)">评论：</i>
              <span>{{item.commentCount}}</span>
            </section>
            <section class="li_footer_item">
              <i class="icon_style iconfont icon-jushoucang"
                 :class="{'icon_style_active':item.like}"
                  @click="like(item)">收藏：</i>
              <span :class="{'is_selected':item.like}">{{item.likeCount}}</span>
            </section>
          </section>

        </li>
      </ul>
      <p class="load_content" v-show="!startShowLoading && showLoading">
        <spinner class="load_icon" type="snake"></spinner>
      </p>
    </section>



    <jm-footer></jm-footer>

    <transition name="loading">
      <spinner class="load_icon" type="snake" v-show="startShowLoading"></spinner>
      <!--<loading v-show="showLoading"></loading>-->
    </transition>
    <transition name="router-slid" mode="out-in">
      <router-view></router-view>
    </transition>



  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex'
  import JmHead from '../../components/header/Head';
  import JmFooter from '../../components/footer/Footer';
  import { Spinner,Toast } from 'mint-ui'


export default {
  data () {
    return {
      selected:1,
      oldSelected: 1,
      artilceList:[],
      defaultArticleList:[],
      defaultOffset:0,
      newArticleList:[],
      newOffset:0,
      likeArticleList:[],
      likeOffset:0,
      result: null,
      preventRepeat: false,
      showLoading: true,
      startShowLoading: true,
      offset: 0,
      loading: false,
      commentBoxVisible:false,
      article: "",

    }
  },
  mounted () {
      // 如果从详情返回并且之前存有对应的查询条件和参数
    // 则直接渲染之前的数据
    if (window.window.sessionStorage.artilceList) {
      this.artilceList = JSON.parse(window.window.sessionStorage.artilceList);
      this.offset = this.artilceList.length;
      this.$nextTick(() => $(window).scrollTop(window.window.sessionStorage.scrollTop));
    } else {
    }
  },
  beforeRouteLeave(to, from, next) {
    // 如果跳转到详情页面，则记录关键数据
    // 方便从详情页面返回到该页面的时候继续加载之前位置的数据
    if (to.path === '/article') {
      // 当前滚动条位置
      window.window.sessionStorage.scrollTop = $(window).scrollTop();
      // 当前页面数据
      window.window.sessionStorage.artilceList = JSON.stringify(this.artilceList);
    }
    $(window).off('scroll');
    next();
  },
  beforeRouteEnter(to, from, next) {
    if (from.path !== '/article') {
      // 页面切换移除之前记录的数据集
//      if (window.window.sessionStorage.tab) {
        window.window.sessionStorage.removeItem('artilceList');
//      }
    }
    next();
  },
  computed: {
  },
  methods: {
    ...mapMutations([
      'SAVE_ARTICLE'
    ]),
    freshen(){
      if (this.oldSelected !== this.selected){
        this.loadMore();
        this.oldSelected = this.selected;
      }
    },

    async loadMore(){
      this.loading = true;

      if (this.selected === 1){
        this.artilceList = this.defaultArticleList;
      }else if(this.selected === 2){
        this.artilceList = this.newArticleList;
      }else if(this.selected === 3){
        this.artilceList = this.likeArticleList;
      }

      //获取信息
      let res = null;
      if (this.selected === 1){
        let url = '/v1/article?userId=' + this.$store.state.userInfo.userId
          + '&start=' + this.defaultOffset
          + '&length=' + this.$store.state.length
        await this.axios.get(url)
          .then(response => {
            res = response.data;
          })
      }else if (this.selected === 2){
        let url = '/v1/article?userId=' + this.$store.state.userInfo.userId
            + '&orderBy=1&desc=1'
            + '&start=' + this.newOffset
            + '&length=' + this.$store.state.length
        await this.axios.get(url)
          .then(response => {
            res = response.data;
          })
      }else if (this.selected === 3){
        let url = '/v1/article?userId=' + this.$store.state.userInfo.userId
          + '&orderBy=2'
          + '&start=' + this.likeOffset
          + '&length=' + this.$store.state.length
        await this.axios.get(url)
          .then(response => {
            res = response.data;
          })
      }


      if (res.success){
        this.startShowLoading = false;
      }else{
        let instance = Toast({message: '网络连接失败', className: 'toast'});
        setTimeout(() => {
          instance.close();
        }, 2000);
      }
      if (this.selected === 1){
        this.defaultOffset += res.result.length;
        this.defaultArticleList = [...this.defaultArticleList, ...res.result];
        this.artilceList = this.defaultArticleList;
      } else if (this.selected === 2){
        this.newOffset += res.result.length;
        this.newArticleList = [...this.newArticleList, ...res.result];
        this.artilceList = this.newArticleList;
      } else if (this.selected === 3){
        this.likeOffset += res.result.length;
        this.likeArticleList = [...this.likeArticleList, ...res.result];
        this.artilceList = this.likeArticleList;
      }

      if (res.result.length > 0){
        this.loading = false;
      }


      if (res.result.length < this.$store.state.length) {
        this.showLoading = false;
        return
      }
    },


    showArticle(item){
      let param = {
          id: item.id
      }
      this.axios.post('/v1/click', param);
      this.SAVE_ARTICLE(item);
      this.preventRepeat = false;
      this.$router.push('/article');

    },

    async upvote(item){
      let url = '/v1/upvote'
      let param={
        userId: this.$store.state.userInfo.userId,
        articleId: item.id
      }
      let res
      if (! item.upvote){
        await this.axios.post(url, param)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          let i = 0;
          for (; i < this.artilceList.length; i ++){
            if (this.artilceList[i].id === item.id){
              this.artilceList[i].upvote = true;
              this.artilceList[i].upvoteCount ++;
              break;
            }
          }
          let instance = Toast({message: '点赞成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      }else{
        let instance = Toast({message: '您已点赞', className: 'toast'});
        setTimeout(() => {
          instance.close();
        }, 2000);
      }
    },

    async comment(item){
        this.article = item;
        this.commentBoxVisible = true;
    },

    async like(item){
      let url = '/v1/like'
      let param={
        userId: this.$store.state.userInfo.userId,
        articleId: item.id
      }
      let res
      if (item.like){
        await this.axios.put(url, param)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          let i = 0;
          for (; i < this.artilceList.length; i ++){
            if (this.artilceList[i].id === item.id){
              this.artilceList[i].like = false;
              this.artilceList[i].likeCount --;
              break;
            }
          }
          i = 0;
          for (; i < this.likeArticleList.length; i ++){
            if (this.likeArticleList[i].id === item.id){
              this.likeArticleList.splice(i,1);
              break;
            }
          }
          let instance = Toast({message: '取消收藏', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);

        }else {
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      }else{
        await this.axios.post(url, param)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          let i = 0;
          for (; i < this.artilceList.length; i ++){
            if (this.artilceList[i].id === item.id){
              this.artilceList[i].like = true;
              this.artilceList[i].likeCount ++;
              break;
            }
          }
          this.likeArticleList.push(item);
          this.likeOffset ++;
          let instance = Toast({message: '收藏成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);

        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      }

    },
  },
  components:{
    Spinner,
    JmHead,
    JmFooter
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">

  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }
  .mint-spinner-snake{
    margin: 0 auto;
  }
</style>

<style lang="scss" scoped>
  @import '../../style/mixin';

  .load_icon{
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;

  }
  .load_content{
    height: 45px;
    width: 100%;

  }

  .center{
    padding-top: 1.5rem;
    padding-bottom: 2rem;
    overflow: hidden;
  }

  .nav{
    background-color: #eaeaea;
    position: fixed;
    z-index: 100;
    left: 0;
    right: 0;
    top: 1.5rem;
    @include wh(100%, 0.88rem);
    display: flex;
    box-shadow: 0 -0.026667rem 0.053333rem rgba(0,0,0,.1);

    .nav-item{
      flex: 1;
      display: flex;
      text-align: center;
      flex-direction: column;
      align-items: center;
      @include sc(.5rem, #666);

      span{
        margin: auto auto;
      }

      .is-selected{
        color: #33CCFF;
      }
    }
  }

  .post_list_ul{
    padding-top: 0.88rem;

    .post_list_li{
      border: solid 1px #d7dde4;
      @include borderRadius(0.1rem);
      border-bottom: solid 10px #eaeaea;


      /*单个文章节点头部 开始*/
      .li_header{
        @include wh(100%, 1.6rem);
        border-bottom: solid 1px #e3e8ee;
        display: flex;

        .li_header_left{
          display: inline-block;
          margin: 0rem 0.5rem;

          .avatar{
            @include wh(1.3rem, 1.3rem);
            @include borderRadius(0.65rem);
            margin-top: 0.15rem;
          }
        }

        .li_header_center{
          flex-direction: column;
          align-items: center;
          display: inline-block;
          margin: auto 0.2rem;
          .nick{
            margin: auto 0;
            font-size: 0.6rem;
            font-weight: bold;
          }

        }

        .li_header_right{
          flex-direction: column;
          align-items: center;
          display: inline-block;
          margin: auto 0.2rem;

          .datetime{
            margin: auto 0;
            font-size: 0.4rem;
            font-weight: bold;
          }
        }
      }


      /* 单个节点中部，内容部分  开始*/
      .li_center{
        padding: 0.2rem 0.5rem;

        .li_center_container{
          background-color: #FFFFFF;
          padding: 0.3rem;


          .img_show{
            display: flex;
            .img_show_item{
              flex: 1;
              display: flex;
              text-align: center;
              flex-direction: column;
              align-items: center;
              margin: 0 0.05rem;
              display: inline-block;
              @include wh(0rem, 3.2rem);
            }
          }
        }
        .li_center_container_active{
          background-color: #FFFFFF;
          padding: 0.3rem;
          display: flex;

          .container{
            flex: 2;
            display: flex;
            flex-direction: column;
            font-size: 0.6rem;

          }

          .img_show{
            flex: 1;
            display: flex;
            .img_show_item{
              @include wh(100%, 3.2rem);
            }
          }
        }

      }

      /* 单个节点尾部  开始*/
      .li_footer{
        border-top: solid 1px #e3e8ee;
        padding-left: 0.5rem;
        display: flex;

        .li_footer_item{
          flex: 1;
          display: flex;
          /*text-align: center;*/
          /*flex-direction: column;*/
          align-items: center;

          .icon_style{
            font-size: 0.6rem;
            display: inline-block;

          }
          span{
            font-size: 0.6rem;
          }

          .icon_style_active{
            color: #33CCFF;
          }

          .is_selected{
            color: #33CCFF;
          }
        }

      }
    }
  }


  span,input{
    font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
  }





</style>
